import { Component, OnInit, Host, ViewChild } from '@angular/core';
import { AppComponent } from '../../../app.component';
import { Page } from '../../../shared/components/table/models/pagination.model';
import { TableRouterLink } from '../../../shared/components/table/models/tableRouterLink.model';
import { TableOptions } from '../../../shared/components/table/models/tableOptions.model';
import { TableComponent, PaginationPositionDisplayEnum } from '../../../shared/components/table/table.component';
import { SpotlightCategory, SpotlightAvailability, SpotlightStatus } from './model/spotlights.model';
import { ColumnOptions, ColumnType } from '../../../shared/components/table/models/columnOptions.model';
import { TableButton, ButtonType } from '../../../shared/components/table/models/tableButton.model';
import { SpotlightsService } from './spotlights.service';
import swal, { SweetAlertOptions } from 'sweetalert2';
import { ToasterService } from 'angular2-toaster';

@Component({
  templateUrl: './spotlights.component.html',
  providers: [SpotlightsService]
})
export class SpotlightsComponent implements OnInit {
  private options: TableOptions;
  public spotlights: any[];
  public selectedSpotlights: string[] = [];
  public count: number;
  public selectedCategory: SpotlightCategory = undefined;
  public categories = SpotlightCategory;
  public paginationPosition = PaginationPositionDisplayEnum.Down;
  public columns: ColumnOptions[] = [
    new ColumnOptions('selected', 'Select', 'col-md-1', false, ColumnType.Buttons),
    new ColumnOptions('name', 'News Item', 'col-md-3', true, ColumnType.Link),
    new ColumnOptions('created', 'Date Added', 'col-md-2', false, ColumnType.DateTime),
    new ColumnOptions('addedBy', 'Added By', 'col-md-2', false, ColumnType.Label),
    new ColumnOptions('status', 'Status', 'col-md-1', false, ColumnType.Label),
    new ColumnOptions('unpublished', 'Unpublished Date', 'col-md-2', false, ColumnType.DateTime),
    new ColumnOptions('availability', 'Availability', 'col-md-1', false, ColumnType.Label)
  ];
  public filter: any = { name: '' };

  @ViewChild('spotlightsTable') spotlightsTable: TableComponent;

  constructor(@Host() private rootComponent: AppComponent,
    private spotlightsService: SpotlightsService,
    private toasterService: ToasterService) { }

  ngOnInit() {
    this.options = new TableOptions('name');
    this.options.filter = this.filter;
    this.getSpotlights();
  }

  public getSpotlights(listOnly: boolean = false) {
    if (listOnly == false) {
      if (this.options.pageOptions.skip > 0) this.spotlightsTable.pageChanged(new Page(0, 20));
      this.spotlightsService.getSpotlightsCount(this.options.filter.name, this.selectedCategory, SpotlightAvailability.All).subscribe(data => {
        this.count = data;
      });
    }

    this.spotlightsService.getSpotlightsList(this.options.filter.name, this.selectedCategory, SpotlightAvailability.All, this.options.pageOptions.skip, this.options.pageOptions.take).subscribe(data => {
      this.spotlights = data.map(spotlight => {
        return {
          selected: [new TableButton('selected', { id: spotlight.id, selected: this.selectedSpotlights.indexOf(spotlight.id) > -1 }, true, ButtonType.CheckBox)],
          name: new TableRouterLink(spotlight.title, true, ['true', spotlight.id]),
          created: new Date(spotlight.dateCreated),
          addedBy: spotlight.addedByUserName,
          status: SpotlightStatus[spotlight.status],
          unpublished: new Date(spotlight.unpublishedDate),
          availability: SpotlightAvailability[spotlight.availableFor]
        }
      });
      this.rootComponent.finishLoading();
    });
  }

  public tableOptionsChanged(tableOptions: TableOptions) {
    this.options = tableOptions;
    this.getSpotlights(tableOptions.pageOptions.listOnly);
  }

  public onSpotlightSelectionChanged(event: any) {
    if (event.selected == false)
      this.selectedSpotlights.push(event.id);
    else
      this.selectedSpotlights.splice(this.selectedSpotlights.indexOf(event.id), 1);
  }

  public deleteSpotlights() {
    const swalOptions: SweetAlertOptions = {
      buttonsStyling: false,
      customClass: 'modal-content',
      showCancelButton: true,
      title: 'Delete News',
      text: 'A number of ' + this.selectedSpotlights.length + ' news will be removed. Are you sure that you want to continue?',
      confirmButtonClass: 'btn btn-primary',
      confirmButtonText: 'Delete',
      cancelButtonClass: 'btn btn btn-outline-dark-grey'
    };
    swal(swalOptions).then(result => {
      if (result && result.value)
        this.spotlightsService.deleteSpotlights(this.selectedSpotlights).subscribe(_ => {
          //update table
          let ids: string[] = this.spotlights.map(x => x.selected[0].actionOptions.id);
          for(var i = 0 ; i < ids.length; i++)
          {
            if(this.selectedSpotlights.indexOf(ids[i]) > -1)
            {
              this.spotlights.splice(i, 1);
              ids.splice(i, 1);
              i--;
            }
          }
          this.spotlightsTable.updateSource(this.spotlights);
          this.selectedSpotlights = [];
          this.toasterService.pop('success', 'Success', 'News deleted successfull.');
        });
    });
  }

  public publishSpotlights() {
    const swalOptions: SweetAlertOptions = {
      buttonsStyling: false,
      customClass: 'modal-content',
      showCancelButton: true,
      title: 'Delete News',
      text: 'A number of ' + this.selectedSpotlights.length + ' news will be published. Are you sure that you want to continue?',
      confirmButtonClass: 'btn btn-primary',
      confirmButtonText: 'Publish',
      cancelButtonClass: 'btn btn btn-outline-dark-grey'
    };
    swal(swalOptions).then(result => {
      if (result && result.value)
      {
        this.spotlightsService.publishSpotlights(this.selectedSpotlights).subscribe(_ => {          
          this.spotlights.filter(x => this.selectedSpotlights.indexOf(x.selected[0].actionOptions.id) > -1).forEach(x=>{                      
            x.status = SpotlightStatus[SpotlightStatus.Published];
            x.selected[0].actionOptions.selected = false;
          });
          this.spotlightsTable.updateSource(this.spotlights);
          this.selectedSpotlights = [];
          this.toasterService.pop('success', 'Success', 'News published successfull.');
        });
      }
    });

  }
}
